options(width=110, device = 'quartz')

library(ggplot2)
library(reshape2)
library(plyr)
library(dplyr)
library(car)

POtoRegion4 <- function (pos, dta=st.info) {
  as.character(dta$REGION4[match(pos, dta$POAbrv)])
}
POtoRegion7 <- function (pos, dta=st.info) {
  as.character(dta$REGION7[match(pos, dta$POAbrv)])
}
mypdf <- function(name, ...) {
  date <- format(Sys.Date(), "%y%m%d")
  pdf(paste(paste(name, collapse=""), date, ".pdf", sep=""), ...)
}

load("party_control_data_161121.RData")
ls()

st.info <- read.csv("StateCodes.csv")
st.info$REGION7[st.info$POAbrv %in% c('HI', 'AK')] <- 'Pacific Coast'
levels(st.info$REGION7)[7] <- 'South'

data.use <- subset(data, abb != 'DC' & year >= 1936)

data.use <-
  plyr:::mutate(data.use,
                GovLib = Policy,
                REGION4 = factor(POtoRegion4(as.character(abb))),
                REGION4 = reorder(REGION4, Policy, mean, na.rm = TRUE),
                REGION7 = factor(POtoRegion7(abb)),
                REGION7 = reorder(REGION7, Policy, mean, na.rm = TRUE),
                REGION5 = Recode(REGION7,
                    'c("Middle Atlantic", "Northeast") = "Northeast";
                        c("East Central", "West Central") = "Midwest";
                        "Rocky Mountain" = "Mountain West"'),
                REGION5 = reorder(REGION5, Policy, mean, na.rm = TRUE),
                GovDem = ifelse(gov_party > 0.5, "Democratic", "Republican"),
                HouseDem = ifelse(hs_dem_control > 0.5, "Democratic",
                    "Republican"),
                SenDem = ifelse(sen_dem_control > 0.5, "Democratic",
                    "Republican"))




mypdf('Figure1_PolLibStTimeSeries-Gov', height = 6)
(ggplot(subset(data.use), aes(x=year, y=Policy))
 + stat_smooth(method = "lm",  formula = y ~ splines::bs(x, 5),
               size = rel(2), se = FALSE, aes(color = GovDem))
 ## + stat_summary(fun.y = mean , geom = 'line', size = 2,
 ##                aes(color = GovDem, group = GovDem))
 + geom_line(aes(group=abb), alpha = .5)
 + geom_text(data = subset(data.use, year == min(year)), show_guide=FALSE,
             aes(label = abb, y = Policy, color = GovDem,
                 x = min(year) - 2 - 2*((rank(Policy) - 1) %% 3)), size = 2)
 + geom_text(data = subset(data.use, year == max(year)), show_guide=FALSE,
             aes(label = abb, y = Policy, color = GovDem,
                 x = max(year) + 2 + 2*((rank(Policy) - 1) %% 3)), size = 2)
 + labs(x = 'Year', y = 'State Goverment Policy Liberalism',
        color = 'Governor\'s Party')
 + scale_x_continuous(breaks = c(min(data.use$year), seq(1950, 2000, 25),
                          max(data.use$year)))
 + scale_color_manual(values = c('blue', 'red'))
 + theme_bw() 
 + theme(legend.position = 'bottom', panel.grid.minor = element_blank())
 )
dev.off()
